//
//  DemoCollectionView.m
//  AFN_UIKit_Read
//
//  Created by tu jinqiu on 2017/8/30.
//  Copyright © 2017年 tu jinqiu. All rights reserved.
//

#import "DemoCollectionView.h"

static NSString *kDemoCellIdentifier = @"kDemoCellIdentifier";

@class DemoCollectionViewDelegate;

@interface DemoCollectionView ()

@property (nonatomic, strong) DemoCollectionViewDelegate *collectionViewDelegate;
@property (nonatomic, weak) id<DemoCollectionViewWPDelegate> wpDelegate;

@end


@interface DemoCollectionViewDelegate : NSObject<UICollectionViewDataSource>

@end

@implementation DemoCollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 200;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DemoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDemoCellIdentifier forIndexPath:indexPath];
    DemoCollectionView *demoCollectionView = (DemoCollectionView *)collectionView;
    if ([demoCollectionView.wpDelegate respondsToSelector:@selector(collectionView:cell:atIndexPath:)]) {
        [demoCollectionView.wpDelegate collectionView:demoCollectionView cell:cell atIndexPath:indexPath];
    }
    
    return cell;
}

@end



@implementation DemoCell

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _imageView = [[UIImageView alloc] initWithFrame:frame];
        [self.contentView addSubview:_imageView];
    }
    
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.imageView.frame = self.contentView.bounds;
}

@end


static CGFloat const g_gap = 3;


@implementation DemoCollectionView

+ (instancetype)DemoCollectionViewWithWPDelegate:(id<DemoCollectionViewWPDelegate>)delegate
{
    CGRect frame = [UIScreen mainScreen].bounds;
    frame = CGRectMake(0, 0, frame.size.width, frame.size.height - 64);
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    CGFloat width = (frame.size.width -  g_gap * 5) / 4;
    layout.itemSize = CGSizeMake(width, width);
    layout.minimumLineSpacing = g_gap;
    layout.minimumInteritemSpacing = g_gap;
    DemoCollectionView *collectionView = [[DemoCollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
    collectionView.collectionViewDelegate = [DemoCollectionViewDelegate new];
    collectionView.dataSource = collectionView.collectionViewDelegate;
    collectionView.wpDelegate = delegate;
    
    [collectionView registerClass:[DemoCell class] forCellWithReuseIdentifier:kDemoCellIdentifier];
    
    return collectionView;
}

@end
